<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">MBTI职业性格测试</h2>
    </div>

    <el-row :gutter="20">
      <el-col :span="currentTest ? 24 : 16">
    <el-card v-if="!currentTest">
      <div class="start-test">
        <h3>开始新的测试</h3>
        <p>本测试共93道题目，每题都有A、B两个选项，请根据您的第一反应选择最符合您的选项。</p>
        <p>测试大约需要15-20分钟完成，请确保有充足的时间和安静的环境。</p>
        <div class="test-buttons">
          <el-button type="primary" @click="handleStartTest">开始测试</el-button>
          <el-button 
            v-if="hasSavedProgress" 
                @click="handleContinueTest"
            type="success" 
          >
            继续上次测试
          </el-button>
        </div>
      </div>
    </el-card>

    <el-card v-else>
      <div class="test-header">
        <el-button @click="cancelTest" size="small" icon="ArrowLeft">返回</el-button>
        <div class="test-progress">
          <el-progress
            :percentage="Math.round((currentQuestionIndex + 1) / questions.length * 100)"
            :format="progressFormat"
            :stroke-width="15"
          />
        </div>
      </div>

      <div v-if="currentQuestion" class="question-container">
        <h3 class="question-title">
              第{{ currentQuestionIndex + 1 }}题：{{ currentQuestion.description }}
        </h3>
        
        <el-radio-group v-model="currentAnswer" class="answer-group">
              <el-radio value="A" border>{{ currentQuestion.optionA }}</el-radio>
              <el-radio value="B" border>{{ currentQuestion.optionB }}</el-radio>
        </el-radio-group>

        <div class="question-actions">
          <el-button
            v-if="currentQuestionIndex > 0"
            @click="previousQuestion"
          >
            上一题
          </el-button>
          <el-button
            type="primary"
            :disabled="!currentAnswer"
            @click="nextQuestion"
          >
            {{ isLastQuestion ? '提交' : '下一题' }}
          </el-button>
        </div>
      </div>
    </el-card>
      </el-col>

      <el-col :span="8" v-if="!currentTest">
        <el-card class="test-history-card">
          <template #header>
            <div class="card-header">
              <span>测试历史</span>
            </div>
          </template>

          <div v-if="testRecords.length" class="history-list">
            <el-timeline>
              <el-timeline-item
                v-for="record in testRecords"
                :key="record.recordId"
                :timestamp="formatDate(record.testDate)"
                placement="top"
              >
                <el-card class="history-record-card">
                  <h4>MBTI类型：{{ record.personalityType }}</h4>
                  <p class="mbti-desc">{{ getMbtiDescription(record.personalityType) }}</p>
                  <div class="record-scores">
                    <div class="score-row">
                      <span>E-I: {{ record.escore || record.eScore || 0 }}-{{ record.iscore || record.iScore || 0 }}</span>
                      <span>S-N: {{ record.sscore || record.sScore || 0 }}-{{ record.nscore || record.nScore || 0 }}</span>
                    </div>
                    <div class="score-row">
                      <span>T-F: {{ record.tscore || record.tScore || 0 }}-{{ record.fscore || record.fScore || 0 }}</span>
                      <span>J-P: {{ record.jscore || record.jScore || 0 }}-{{ record.pscore || record.pScore || 0 }}</span>
                    </div>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
          <div v-else class="empty-history">
            <el-empty description="暂无测试记录" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 测试结果对话框 -->
    <el-dialog
      title="测试结果"
      v-model="showResult"
      width="700px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="result-container">
        <h3>您的MBTI类型是：{{ testResult.personalityType }}</h3>
        <h4 v-if="personalityType && personalityType.name">
          {{ personalityType.name }}
        </h4>
        
        <div class="type-scores">
          <div class="score-item">
            <span>外向 (E) {{ testResult.escore || testResult.eScore || 0 }} - {{ testResult.iscore || testResult.iScore || 0 }} (I) 内向</span>
            <el-progress
              :percentage="calculatePercentage(testResult.escore || testResult.eScore, testResult.iscore || testResult.iScore)"
              :format="() => ''"
              :stroke-width="10"
              :color="testResult.personalityType?.includes('E') ? '#409EFF' : '#CFE3FC'"
            />
          </div>
          <div class="score-item">
            <span>感觉 (S) {{ testResult.sscore || testResult.sScore || 0 }} - {{ testResult.nscore || testResult.nScore || 0 }} (N) 直觉</span>
            <el-progress
              :percentage="calculatePercentage(testResult.sscore || testResult.sScore, testResult.nscore || testResult.nScore)"
              :format="() => ''"
              :stroke-width="10"
              :color="testResult.personalityType?.includes('S') ? '#409EFF' : '#CFE3FC'"
            />
          </div>
          <div class="score-item">
            <span>思维 (T) {{ testResult.tscore || testResult.tScore || 0 }} - {{ testResult.fscore || testResult.fScore || 0 }} (F) 情感</span>
            <el-progress
              :percentage="calculatePercentage(testResult.tscore || testResult.tScore, testResult.fscore || testResult.fScore)"
              :format="() => ''"
              :stroke-width="10"
              :color="testResult.personalityType?.includes('T') ? '#409EFF' : '#CFE3FC'"
            />
          </div>
          <div class="score-item">
            <span>判断 (J) {{ testResult.jscore || testResult.jScore || 0 }} - {{ testResult.pscore || testResult.pScore || 0 }} (P) 知觉</span>
            <el-progress
              :percentage="calculatePercentage(testResult.jscore || testResult.jScore, testResult.pscore || testResult.pScore)"
              :format="() => ''"
              :stroke-width="10"
              :color="testResult.personalityType?.includes('J') ? '#409EFF' : '#CFE3FC'"
            />
          </div>
        </div>
        
        <div class="type-description" v-if="personalityType">
          <el-tabs type="border-card">
            <el-tab-pane label="类型描述">
              <div class="tab-content">
                <p>{{ personalityType.description || '暂无描述' }}</p>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="领导风格">
              <div class="tab-content">
                <p>{{ personalityType.leadershipStyle || '暂无领导风格描述' }}</p>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="学习风格">
              <div class="tab-content">
                <p>{{ personalityType.learningStyle || '暂无学习风格描述' }}</p>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="解决问题方式">
              <div class="tab-content">
                <p>{{ personalityType.problemSolvingStyle || '暂无解决问题方式描述' }}</p>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="工作环境">
              <div class="tab-content">
                <p>{{ personalityType.workEnvironment || '暂无工作环境描述' }}</p>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="潜在缺点">
              <div class="tab-content">
                <p>{{ personalityType.potentialWeaknesses || '暂无潜在缺点描述' }}</p>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="发展建议">
              <div class="tab-content">
                <p>{{ personalityType.developmentSuggestions || '暂无发展建议' }}</p>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="finishTest">完成</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'StudentTestPage'
}
</script>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../stores/user'
import request from '../../utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

// 数据
const questions = ref([])
const currentTest = ref(null)
const currentQuestionIndex = ref(0)
const currentAnswer = ref('')
const answers = ref({})
const showResult = ref(false)
const testResult = ref(null)
const personalityType = ref(null)
const hasSavedProgress = ref(false)
const loading = ref(false)
const testRecords = ref([])

// 本地存储键名
const getStorageKey = () => {
  return `mbti_test_progress_${userStore.userInfo.userId}`
}

// 保存答题进度到本地存储
const saveProgress = () => {
  if (!currentTest.value) return
  
  const progressData = {
    testId: currentTest.value.recordId,
    questionIndex: currentQuestionIndex.value,
    answers: answers.value,
    timestamp: new Date().getTime()
  }
  
  localStorage.setItem(getStorageKey(), JSON.stringify(progressData))
  hasSavedProgress.value = true
}

// 加载本地存储的答题进度
const loadProgress = () => {
  try {
    const progressData = localStorage.getItem(getStorageKey())
    if (!progressData) return null
    
    return JSON.parse(progressData)
  } catch (error) {
    console.error('加载答题进度失败:', error)
    return null
  }
}

// 清除本地存储的答题进度
const clearProgress = () => {
  localStorage.removeItem(getStorageKey())
  hasSavedProgress.value = false
}

// 检查是否有保存的进度
const checkSavedProgress = () => {
  const progress = loadProgress()
  hasSavedProgress.value = !!progress
  return progress
}

// 计算属性
const currentQuestion = computed(() => {
  return questions.value[currentQuestionIndex.value]
})

const isLastQuestion = computed(() => {
  return currentQuestionIndex.value === questions.value.length - 1
})

// 方法
const loadQuestions = async () => {
  loading.value = true
  try {
    const response = await request.get('/questions/list')
    questions.value = response.data
    
    // 检查是否有保存的进度
    checkSavedProgress()
  } catch (error) {
    console.error('获取题目失败:', error)
    ElMessage.error('获取题目失败')
  } finally {
    loading.value = false
  }
}

const loadTestHistory = async () => {
  try {
    const response = await request.get(`/test-records/user/${userStore.userInfo.userId}`)
    if (response.data) {
      // 确保所有记录分数字段都是数字类型，并处理不同的命名方式
      testRecords.value = response.data.map(record => {
        // 处理驼峰式和小写命名
        const processedRecord = {
          ...record,
          eScore: Number(record.eScore || 0),
          iScore: Number(record.iScore || 0),
          sScore: Number(record.sScore || 0),
          nScore: Number(record.nScore || 0),
          tScore: Number(record.tScore || 0),
          fScore: Number(record.fScore || 0),
          jScore: Number(record.jScore || 0),
          pScore: Number(record.pScore || 0),
          
          escore: Number(record.escore || record.eScore || 0),
          iscore: Number(record.iscore || record.iScore || 0),
          sscore: Number(record.sscore || record.sScore || 0),
          nscore: Number(record.nscore || record.nScore || 0),
          tscore: Number(record.tscore || record.tScore || 0),
          fscore: Number(record.fscore || record.fScore || 0),
          jscore: Number(record.jscore || record.jScore || 0),
          pscore: Number(record.pscore || record.pScore || 0)
        };
        return processedRecord;
      });
    }
  } catch (error) {
    console.error('获取测试历史失败:', error);
    ElMessage.error('获取测试历史失败');
  }
}

// 格式化答案数据，用于提交
const formatAnswers = () => {
  // 将答案转换为API所需格式
  const formattedAnswers = {}
  for (const [questionId, answer] of Object.entries(answers.value)) {
    formattedAnswers[parseInt(questionId, 10)] = answer
  }
  return formattedAnswers
}

const handleStartTest = () => {
  // 检查是否有保存的进度
  const savedProgress = checkSavedProgress()
  
  if (savedProgress) {
    // 如果有保存的进度，询问用户是否确定开始新测试
    ElMessageBox.confirm(
      '开始新测试会覆盖正在答题的进度，确定开始新的答题吗？',
      '警告',
      {
        confirmButtonText: '开始答题',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(() => {
        // 用户确认开始新测试
        createNewTest()
      })
      .catch(() => {
        // 用户取消，不做任何操作
      })
  } else {
    // 没有保存的进度，直接开始新测试
    createNewTest()
  }
}

// 创建新测试
const createNewTest = async () => {
  try {
    const response = await request.post('/test-records', {
      userId: userStore.userInfo.userId
    })
    if (response && response.data) {
      currentTest.value = response.data
      currentQuestionIndex.value = 0
      answers.value = {}
      currentAnswer.value = ''
      
      // 清除之前的进度
      clearProgress()
    }
  } catch (error) {
    console.error('开始测试失败:', error)
    ElMessage.error('开始测试失败')
  }
}

// 处理继续测试
const handleContinueTest = async () => {
  const savedProgress = loadProgress()
  
  if (!savedProgress) {
    ElMessage.error('没有找到保存的测试进度')
    return
  }
  
  try {
    // 获取测试记录
    const response = await request.get(`/test-records/${savedProgress.testId}`)
    currentTest.value = response.data
    
    // 恢复答题进度
    currentQuestionIndex.value = savedProgress.questionIndex
    answers.value = savedProgress.answers
    
    // 设置当前题目的答案
    if (currentQuestion.value) {
      currentAnswer.value = answers.value[currentQuestion.value.questionId] || ''
    }
    
    ElMessage.success('已恢复上次答题进度')
  } catch (error) {
    console.error('恢复测试失败:', error)
    ElMessage.error('恢复测试失败，将重新开始测试')
    createNewTest()
  }
}

const progressFormat = (percentage) => {
  return `${currentQuestionIndex.value + 1}/${questions.value.length}`
}

const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
    currentAnswer.value = answers.value[currentQuestion.value.questionId] || ''
    saveProgress()
  }
}

const nextQuestion = async () => {
  answers.value[currentQuestion.value.questionId] = currentAnswer.value
  
  if (isLastQuestion.value) {
    await submitTest()
  } else {
    currentQuestionIndex.value++
    currentAnswer.value = answers.value[currentQuestion.value.questionId] || ''
    saveProgress()
  }
}

const submitTest = async () => {
  try {
    console.log('提交答案:', formatAnswers());
    
    const response = await request.post(
      `/test-records/${currentTest.value.recordId}/submit-answers`,
      formatAnswers()
    )
    
    console.log('提交答案响应:', response);
    
    if (response && response.data) {
      testResult.value = response.data;
      console.log('测试结果原始数据:', JSON.stringify(testResult.value));
    
      // 统一处理分数字段，支持驼峰式和小写两种命名
      const processScores = (result) => {
        // 处理驼峰式命名
        result.eScore = Number(result.eScore || 0);
        result.iScore = Number(result.iScore || 0);
        result.sScore = Number(result.sScore || 0);
        result.nScore = Number(result.nScore || 0);
        result.tScore = Number(result.tScore || 0);
        result.fScore = Number(result.fScore || 0);
        result.jScore = Number(result.jScore || 0);
        result.pScore = Number(result.pScore || 0);
    
        // 处理小写命名
        result.escore = Number(result.escore || result.eScore || 0);
        result.iscore = Number(result.iscore || result.iScore || 0);
        result.sscore = Number(result.sscore || result.sScore || 0);
        result.nscore = Number(result.nscore || result.nScore || 0);
        result.tscore = Number(result.tscore || result.tScore || 0);
        result.fscore = Number(result.fscore || result.fScore || 0);
        result.jscore = Number(result.jscore || result.jScore || 0);
        result.pscore = Number(result.pscore || result.pScore || 0);
        
        return result;
      };
      
      // 处理当前测试结果
      testResult.value = processScores(testResult.value);
      console.log('处理后的测试结果数据:', testResult.value);
    
      // 获取性格类型详细信息
    try {
      const typeResponse = await request.get(
          `/personality-types/code/${testResult.value.personalityType}`
        )
      
      if (typeResponse && typeResponse.data) {
        personalityType.value = typeResponse.data;
      } else {
          personalityType.value = {
            code: testResult.value.personalityType,
            name: `${testResult.value.personalityType}类型`,
            description: '暂无描述'
          }
        }
      } catch (error) {
        console.error('获取性格类型详情失败:', error)
        personalityType.value = {
          code: testResult.value.personalityType,
          name: `${testResult.value.personalityType}类型`,
          description: '暂无描述'
        }
    }
    
    // 显示结果对话框
      showResult.value = true
    
    // 清除进度，因为测试已完成
      clearProgress()
    }
  } catch (error) {
    console.error('提交测试失败:', error)
    ElMessage.error('提交测试失败')
  }
}

const finishTest = () => {
  showResult.value = false
  currentTest.value = null
  // 重新加载测试历史
  loadTestHistory()
  router.push('/student/test')
}

const cancelTest = () => {
  ElMessageBox.confirm(
    '确定要退出当前测试吗？您的答题进度将被保存，下次可以继续。',
    '提示',
    {
      confirmButtonText: '保存并退出',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 保存进度到本地存储
      saveProgress()
      
      // 关闭当前测试
      currentTest.value = null
      
      ElMessage({
        type: 'success',
        message: '答题进度已保存，下次可继续答题',
      })
    })
    .catch(() => {
      // 用户取消操作，不做任何处理
    })
}

// 监听答题进度变化，保存到本地
watch(() => currentQuestionIndex.value, () => {
  if (currentTest.value) {
    saveProgress()
  }
})

onMounted(() => {
  loadQuestions()
  loadTestHistory()
})

// 计算百分比，用于进度条显示
const calculatePercentage = (score1, score2) => {
  // 确保参数是数字
  const s1 = Number(score1 || 0);
  const s2 = Number(score2 || 0);
  
  // 防止除以零错误
  if (s1 === 0 && s2 === 0) return 50; // 如果两个分数都是0，显示中间位置
  
  // 计算百分比：score1 / (score1 + score2) * 100
  const total = s1 + s2;
  return Math.round((s1 / total) * 100);
}

// 添加样式
const style = document.createElement('style');
style.textContent = `
.type-scores .score-item {
  margin: 20px 0;
}

.type-scores .score-item span {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.type-scores .score-item .el-progress {
  margin-top: 5px;
}

.type-scores .score-item .el-progress-bar__outer {
  background-color: #E9EEF3;
}

.type-scores .score-item .el-progress-bar__inner {
  transition: all 0.3s ease;
}
`;
document.head.appendChild(style);

const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleDateString()
}

const getMbtiDescription = (mbtiType) => {
  const descriptions = {
    'INTJ': '内倾、直觉、思考、判断',
    'INTP': '内倾、直觉、思考、知觉',
    'ENTJ': '外倾、直觉、思考、判断',
    'ENTP': '外倾、直觉、思考、知觉',
    'INFJ': '内倾、直觉、情感、判断',
    'INFP': '内倾、直觉、情感、知觉',
    'ENFJ': '外倾、直觉、情感、判断',
    'ENFP': '外倾、直觉、情感、知觉',
    'ISTJ': '内倾、感觉、思考、判断',
    'ISFJ': '内倾、感觉、情感、判断',
    'ESTJ': '外倾、感觉、思考、判断',
    'ESFJ': '外倾、感觉、情感、判断',
    'ISTP': '内倾、感觉、思考、知觉',
    'ISFP': '内倾、感觉、情感、知觉',
    'ESTP': '外倾、感觉、思考、知觉',
    'ESFP': '外倾、感觉、情感、知觉'
  }
  return descriptions[mbtiType] || '未知类型'
}
</script>

<style scoped>
.start-test {
  text-align: center;
  padding: 40px 0;
}

.test-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.test-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.test-progress {
  flex: 1;
  margin-left: 15px;
}

.question-container {
  max-width: 800px;
  margin: 0 auto;
}

.question-title {
  margin-bottom: 30px;
  font-size: 18px;
  color: #303133;
}

.answer-group {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.answer-group :deep(.el-radio) {
  height: auto;
  padding: 15px;
  margin: 0;
  white-space: normal;
  line-height: 1.5;
}

.question-actions {
  margin-top: 30px;
  display: flex;
  justify-content: space-between;
}

/* 测试结果样式 */
.result-container {
  text-align: center;
}

.result-container h3 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.result-container h4 {
  font-size: 18px;
  color: #606266;
  margin-bottom: 25px;
  font-weight: normal;
}

.type-scores {
  margin: 30px 0;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}

.type-description {
  margin-top: 30px;
  text-align: left;
}

.tab-content {
  padding: 15px;
  line-height: 1.8;
  font-size: 14px;
  color: #606266;
  max-height: 300px;
  overflow-y: auto;
}

.tab-content p {
  margin: 0;
  white-space: pre-line; /* 保留换行符 */
}

.test-history-card {
  height: 100%;
}

.history-list {
  max-height: calc(100vh - 250px);
  overflow-y: auto;
  padding-right: 10px;
}

.history-record-card {
  margin-bottom: 10px;
}

.history-record-card h4 {
  margin: 0 0 10px;
  color: #303133;
  font-size: 16px;
}

.record-scores {
  margin-top: 10px;
  font-size: 13px;
  color: #606266;
}

.score-row {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
}

.mbti-desc {
  font-size: 13px;
  color: #909399;
  margin: 5px 0;
  line-height: 1.4;
}

.empty-history {
  padding: 40px 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 